package com.antis.olsl.library;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.alibaba.android.arouter.launcher.ARouter;
import com.antis.olsl.base.utils.LogUtils;
import com.antis.olsl.library.bean.UserInfo;
import com.antis.olsl.library.dao.UserInfoControl;
import com.antis.olsl.library.db.DaoMaster;
import com.antis.olsl.library.db.DaoSession;

public class MyApplication extends MultiDexApplication {

    private static MyApplication mInstance;
    private static DaoSession daoSession;
    private static UserInfo userInfo;

    public static UserInfo getUserInfo() {
        return userInfo == null ? UserInfoControl.getUserInfo() : userInfo;
    }

    public static void setUserInfo(UserInfo userInfo) {
        MyApplication.userInfo = userInfo;
        if (userInfo == null) {
            UserInfoControl.delete();
        } else {
            UserInfoControl.insert(userInfo);
        }
    }

    public static void delUserInfo() {
        UserInfoControl.delete();
        MyApplication.userInfo = null;
    }

    public static MyApplication getInstance() {
        if (mInstance == null) {
            throw new IllegalStateException("Not yet initialized");
        }
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (mInstance != null) {
            throw new IllegalStateException("Not a singleton");
        }
        mInstance = this;

        if (BuildConfig.DEBUG) {
            ARouter.openLog();
            ARouter.openDebug();
        }
        LogUtils.init();
        ARouter.init(this);

        setupDatabase();
    }

    /**
     * 配置数据库
     */
    private void setupDatabase() {
        //创建数据库"
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "schoolmanager.db", null);
        //获取可写数据库
        SQLiteDatabase db = helper.getWritableDatabase();
        //获取数据库对象
        DaoMaster daoMaster = new DaoMaster(db);
        //获取Dao对象管理者
        daoSession = daoMaster.newSession();
    }

    public static DaoSession getDaoInstant() {
        return daoSession;
    }

    //方法数超过65535
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
